import axios from "axios";
import {
	getToken,
	removeToken
} from './token.js';
import codeMessage from './code.js';

axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.responseType = 'json';
axios.defaults.withCredentials = false;

const service = axios.create({
	baseURL: 'http://localhost:8712',
	timeout: 30 * 1000
})

service.interceptors.request.use(config => {
	if (config.headers?.isToken !== false && getToken()) config.headers['authorization'] = getToken();
	return config;
}, error => {
	return Promise.reject(error);
});

service.interceptors.response.use(response => {
	const { status, data } = response;
	const { code = 88888, message = codeMessage[status], success = true } = data;
	if (!success) {
		if (status === 401) {
			removeToken();
		}
		return Promise.reject({
			status,
			code,
			message
		});
	} else {
		return Promise.resolve(response);
	}
}, error => {
	if (error.response?.status) {
		const { status, data } = error.response;
		const { code, message = codeMessage[status || 'default'] } = data;
		return Promise.reject({
			status,
			code,
			message
		});
	} else {
		return Promise.reject(error);
	}
});

export default service;
